package com.hspedu.ticket;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author 谷其昊
 * @version 1.0
 * @date 2022/2/15
 * @time 14:42
 *
 *使用多线程模拟三个窗口同时售票100张
 */
public class SellTicket {
    public static void main(String[] args) throws InterruptedException {
        new Wicked1().start();
        new Wicked1().start();
        new Wicked1().start();
    }
}

class Wicked1 extends Thread{
    /**
     *     多个线程共享ticketNum
     */
    private static int ticketNum = 100;
    private static A a = new A();
    private boolean loop = true;
    private static final Lock lock = new ReentrantLock();

    @Override
    public void run() {
        while (loop){

           sellTickets();

        }
    }

    public void sellTickets(){
        synchronized (a){

            if (ticketNum <= 0) {
                System.out.println(Thread.currentThread().getName() +"售票结束...");
                loop = false;
                return;
            }

            //休眠50毫秒, 模拟
            try {
                Thread.sleep(50);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            System.out.println("窗口 " + Thread.currentThread().getName() +
                    " 售出一张票"
                    + " 剩余票数=" + (--ticketNum));
        }
    }
}

class A{}